package com.lanou.pro;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.List;

/**
 * @author zyj
 * @date 2022年06月11日 15:00
 */
public class ServerHandler implements Runnable {
    private List<Socket> list;
    private Socket socket;

    public ServerHandler(List<Socket> list, Socket socket) {
        this.list = list;
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            list.add(socket);
            System.out.println("在线人数：" + list.size());
            PrintStream ps = new PrintStream(System.out);
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (true) {
                String message = reader.readLine();
                ps.println(
                        socket.getInetAddress().getHostAddress()
                                + ":" + socket.getInetAddress().getHostName()
                                + "发的消息：" + message);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            list.remove(socket);
            System.out.println(socket.getInetAddress().getHostAddress() + ":" + socket.getPort() + "下线");
            System.out.println("目前在线人数" + list.size());
        }
    }
}
